﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Pathology.Control;
using PathologyBLL.Service;
using PathologyDAL.Modle;
using PathologyDAL.Service;
using Sunny.UI;

namespace Pathology.UI
{
    public partial class TumourPage : UIPage
    {
        private TumourManageServices services;

        public TumourPage()
        {
            InitializeComponent();
        }

        private async void TumourForm_Initialize(object sender, EventArgs e)
        {
            services = new TumourManageServices();

            await LoadExitsItem();
        }

        private async Task LoadExitsItem()
        {
            var list = await services.LoadAsync(uiTextBoxFilter.Text);

            LoaduiListBoxItems(list);
        }

        private void LoaduiListBoxItems(List<Tumour> tumours)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(() =>
                {
                    uiListBoxItems.Items.Clear();
                    foreach (Tumour item in tumours)
                    {
                        uiListBoxItems.Items.Add(item);
                    }
                });
            }
            else
            {
                uiListBoxItems.Items.Clear();
                foreach (Tumour item in tumours)
                {
                    uiListBoxItems.Items.Add(item);
                }
            }
        }

        private async void uiTextBoxFilter_TextChanged(object sender, EventArgs e)
        {
            await LoadExitsItem();
        }

        private async void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            //新增

            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            option.Text = $"新增肿瘤";

            option.AddText("Name", "名称", null, true);

            UIEditForm frm = new UIEditForm(option);
            frm.Render();
            frm.CheckedData += Frm_CheckedData;
            frm.ShowDialog();

            if (frm.IsOK)
            {
                //处理逻辑
                await Task.Run(async () =>
                {
                    string Names = frm["Name"].ToString();
                    if (!string.IsNullOrEmpty(Names))
                    {
                        string message = await services.AddTumourAsync(Names.Trim());
                        this.ShowInfoTip(message, 2000);
                        await LoadExitsItem();
                    }
                });
            }

            frm.Dispose();
        }

        private bool Frm_CheckedUpdateData(object sender, UIEditForm.EditFormEventArgs e)
        {
            string name = e.Form["Name"].ToString().Trim();

            if (name.Contains(" "))
            {
                this.ShowErrorTip($"修改模式下不支持多输入！", 2000);
                return false;
            }
            return Task.Run(async () =>
            {
                string tumour = await services.CheckTumourAsync(name);
                if (tumour.Length == 0)
                {
                    return true;
                }
                else
                {
                    this.ShowErrorTip($"[{tumour}]已存在，请重新输入！", 2000);
                    return false;
                }
            }).Result;
        }

        private async void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            //删除
            if (uiListBoxItems.SelectedIndex > -1)
            {
                Tumour selectTumour = uiListBoxItems.SelectedItem as Tumour;
                if (selectTumour != null)
                {
                    if (this.ShowAskDialog($"确认删除{selectTumour.Name}"))
                    {
                        var res = await services.DeleteAsync(selectTumour.ID);
                        if (res.Success)
                        {
                            await LoadExitsItem();
                            this.ShowInfoTip("删除成功！", 1500);
                        }
                        else
                        {
                            await LoadExitsItem();
                            this.ShowErrorTip("删除失败", 1500);
                        }
                    }
                }
            }
        }

        private async void uiSymbolButton4_ClickAsync(object sender, EventArgs e)
        {
            await LoadExitsItem();
        }

        private async void uiSymbolButton2_ClickAsync(object sender, EventArgs e)
        {
            if (uiListBoxItems.SelectedIndex > -1)
            {
                Tumour tumour = (Tumour)uiListBoxItems.SelectedItem;
                if (null != tumour)
                {
                    UIEditOption option = new UIEditOption();
                    option.AutoLabelWidth = true;
                    option.Text = $"修改肿瘤名称";
                    option.AddText("Name", "名称:", tumour.Name, true);
                    UIEditForm frm = new UIEditForm(option);
                    frm.Render();
                    frm.CheckedData += Frm_CheckedUpdateData;
                    frm.ShowDialog();

                    if (frm.IsOK)
                    {
                        //处理逻辑

                        //处理逻辑
                        await Task.Run(async () =>
                        {
                            string Names = frm["Name"].ToString();

                            if (!string.IsNullOrEmpty(Names))
                            {
                                CheckResult result = await services.UpdateNameAsync(
                                    tumour,
                                    Names.Trim()
                                );
                                this.ShowInfoTip(result.Message, 2000);
                                await LoadExitsItem();
                            }
                        });
                    }

                    frm.Dispose();
                }
            }

            //新增
        }

        private bool Frm_CheckedData(object sender, UIEditForm.EditFormEventArgs e)
        {
            string name = e.Form["Name"].ToString().Trim();

            var list = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            if (list.Length != list.Distinct().Count())
            {
                this.ShowErrorTip($"输入的文字有重复，请重新输入！", 2000);
                return false;
            }

            return Task.Run(async () =>
            {
                string filterConditions = await services.CheckTumourAsync(name);
                if (filterConditions.Length == 0)
                {
                    return true;
                }
                else
                {
                    this.ShowErrorTip($"[{filterConditions}]已存在，请重新输入！", 2000);
                    return false;
                }
            }).Result;
        }

        private Tumour selectTumour;

        private void uiListBoxItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            //修改了

            if (uiListBoxItems.SelectedIndex > -1)
            {
                selectTumour = uiListBoxItems.SelectedItem as Tumour;
                if (selectTumour != null)
                {
                    DisPlayTumour(selectTumour);
                }
            }
        }

        private async void DisPlayTumour(Tumour tumour)
        {
            uiFlowLayoutPanelDisPlay.Clear();
            //从数据库中去拿数据

            var conditions = await services.LoadTumourConditionByTumourAsync(tumour);

            //过滤
            List<TumourConditionDisPlay> filters;
            if (uiComboBoxFilter.SelectedIndex > -1)
            {
                filters = conditions
                    .Where(c => c.FilterConditionInfo.Filter == (Filter)uiComboBoxFilter.SelectedIndex)
                    .ToList();
            }
            else
            {
                filters = conditions;
            }
            var conditionsOrder = filters.OrderBy(c => c.FilterConditionInfo.Priority);
            foreach (var condition in conditionsOrder)
            {
                ConditionDisPlay conditionDisPlay = new ConditionDisPlay(condition);
                conditionDisPlay.SetDPIScale();
                uiFlowLayoutPanelDisPlay.Add(conditionDisPlay);
            }
        }



        private void uiSymbolButtonAddCondition_Click(object sender, EventArgs e)
        {
            //添加条件 需要
            if (uiListBoxItems.SelectedIndex > -1)
            {
                selectTumour = uiListBoxItems.SelectedItem as Tumour;
                if (selectTumour != null)
                {
                    AddFilterCondition addFilterCondition = new AddFilterCondition(
                        selectTumour,
                        () =>
                        {
                            this.ShowSuccessTip("操作成功！");
                            DisPlayTumour(selectTumour);
                        }
                    );
                    addFilterCondition.ShowDialog();
                }
            }
            else
            {
                this.ShowErrorTip("请先选择好肿瘤！！");
            }
        }

        private void uiSymbolButton7_Click(object sender, EventArgs e)
        {
            if (uiListBoxItems.SelectedIndex > -1)
            {
                selectTumour = uiListBoxItems.SelectedItem as Tumour;
                if (selectTumour != null) { }
            }
            else
            {
                this.ShowErrorTip("请先选择好肿瘤！！");
            }
        }
    }
}
